﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DotNetStar.TheKing.Web.Pages.User.Setting
{
    public class BindAccountModel : PageModel
    {
        private readonly UserService _userService;
        public BindAccountModel(UserService userService)
        {
            _userService = userService;
        }
        public bool HasPassword { get; set; }

        [BindProperty]
        [Display(Name ="密码")]
        [DataType(DataType.Password)]
        [Required(ErrorMessage = "{0}是必填项"), StringLength(25, ErrorMessage = "{0}必须在 {2}-{1} 个字符", MinimumLength = 8)]
        public string Password { get; set; }

        [BindProperty]
        [Display(Name = "确认密码")]
        [Compare("Password", ErrorMessage = "两次密码不一致")]
        [DataType(DataType.Password)]
        public string ConfirmPassword { get; set; }

        public async Task OnGetAsync()
        {
            var user = await _userService.GetByIdAsync(User.Identity.UserId());
            this.HasPassword = !user.Password.IsNullOrWhiteSpace();
        }

        public async Task<IActionResult> OnPostBindPasswordAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            var user = await _userService.GetByIdAsync(User.Identity.UserId());

            var salt= PasswordHasher.GeneratePasswordSalt();
            var pwd= PasswordHasher.GeneratePassword(this.Password, salt);
            user.SetPassword(pwd, salt);

            try
            {
                await _userService.UpdateUserAsync(user);
                ViewData["Success"] = true;
            }catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            return Page();
        }
    }
}